﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web.Services.Protocols;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;
using MSPE.Public.FOSS.AutoStatusPlus.Common;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.SPValidators;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.Commands
{
    class AspSetEvent : SPOperation
    {
        #region Constructors
        /// <summary>
        /// Constructs a new instance of the <see cref="AspSetEvent" /> class.
        /// </summary>
        public AspSetEvent()
        {
            SPParamCollection _parameters = new SPParamCollection
                                               {
                                                   new SPParam(GlobalConstants.UrlParamName, GlobalConstants.UrlParamName, true, null,
                                                               new SPUrlValidator(),
                                                               "Please specify the PWA site URL."),
                                                   new SPParam(GlobalConstants.EventParamName, 
                                                               GlobalConstants.EventParamName, true,
                                                               null, new SPEnumValidator(typeof(TimesheetEventEnum)),
                                                               "Please specify the event name.")
                                               };

            StringBuilder _sb = new StringBuilder();
            _sb.AppendLine("-url <URL of PWA Site>");
            _sb.AppendLine("\t-event <Name of supported Timesheet Event>");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("\tThis command controls which timesheet event AutoStatusPlus");
            _sb.AppendLine("\tresponds to.");
            _sb.AppendLine();
            _sb.AppendLine("\tValid values for the -event parameter are:");
            _sb.AppendLine("\t\tOnUpdated");
            _sb.AppendLine("\t\tOnUpdating");
            _sb.AppendLine("\t\tOnSubmitted");
            _sb.AppendLine("\t\tOnSubmitting");
            _sb.AppendLine("\t\tOnReviewed -- Acts only on timesheet approvals");
            _sb.AppendLine("\t\tOnReviewing -- Acts only on timesheet approvals");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("The event parameter is set to OnUpdating by default.");

            Init(_parameters, _sb.ToString());
        } // AspSetEvent()
        #endregion // Constructors

        #region Methods
        #region Overrides
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            throw new NotImplementedException();
        } // Execute()

        /// <summary>
        /// Gets the help message.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public override string GetHelpMessage(string command)
        {
            return HelpMessage;
        } // GetHelpMessage()

        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Run(string command, StringDictionary keyValues, out string output)
        {
            SPSite _site = null;
            SPWeb _pwaWeb = null;

            try
            {
                #region Read configuration settings from command line
                output = string.Empty;

                InitParameters(keyValues);

                // Read params into local fields
                string _event = Params[GlobalConstants.EventParamName].Value;
                string _url = Params[GlobalConstants.UrlParamName].Value.TrimEnd('/');

                _site = new SPSite(_url);

                if (_site.Url != _url) throw new Exception("You may only configure Project Web Access Sites.");

                _pwaWeb = _site.RootWeb;

                if (_pwaWeb == null) throw new Exception("Could not load the Site at the specified URL.");

                if (_pwaWeb.WebTemplateId != GlobalConstants.PwaSiteTemplateId) throw new Exception("You may only configure Project Web Access Sites.");
                #endregion // Read configuration settings from command line

                // Load current settings
                Settings _loadedSettings = Settings.LoadSettings(_pwaWeb);
                TimesheetEventEnum _eventAsEnum =
                    (TimesheetEventEnum) Enum.Parse(typeof (TimesheetEventEnum), _event);

                if (_eventAsEnum != _loadedSettings.Event)
                {
                    Utility.UnregisterEventHandler(_pwaWeb, _loadedSettings.Event);

                    // Update setting
                    _loadedSettings.Event = _eventAsEnum;

                    Settings.UpdateSettings(_pwaWeb, _loadedSettings);

                    Utility.RegisterEventHandler(_pwaWeb, _loadedSettings.Event);
                } // End if
                // Use the ErrorCodes enum to return error codes: 
                // ErrorCodes.SyntaxError
                // ErrorCodes.GeneralError

                // Return 0 for success.

                output = "Operation completed successfully.\r\nPlease allow time for Project Server to process the change.";
                return 0;
            } // End try

            catch (SoapException ex)
            {
                throw Utility.ExpandPsiException(ex);
            } // End catch

            catch (Exception ex)
            {
                throw new Exception("Error encountered while setting event:\n\n" + ex.ToString());
            } // End catch

            finally
            {
                if (_pwaWeb != null) _pwaWeb.Dispose();
                if (_site != null) _site.Dispose();
            } // End finally
        } // Run()
        #endregion // Overrides
        #endregion // Methods
    }
}
